package com.example.dockerdemo.controller;


import cn.hutool.core.util.RandomUtil;
import com.example.dockerdemo.entity.User;
import com.example.dockerdemo.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2022-12-08 17:19:26
 */
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;
    private final RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/addUserByCount")
    public boolean addUserByCount(int num) {
        List<User> userList = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            userList.add(
                    User.builder()
                            .name(RandomUtil.randomString(6))
                            .sex(RandomUtil.randomInt(0, 1))
                            .build());
        }
        return userService.saveBatch(userList);
    }

    @GetMapping("/getUserList")
    public List<User> getUserList() {
        return userService.list();
    }

    @GetMapping("/getById")
    public User getById(Integer id) {
        User user = (User) redisTemplate.opsForValue().get("cache:" + id);
        if (user == null) {
            user = userService.getById(id);
            log.info("getById将数据放入Redis , key = cache:{}, data = {}", id, user);
            redisTemplate.opsForValue().set("cache:" + id, user);
        }
        return user;
    }

}
